<template>
  <div class="setting-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>

      <el-table :data="settingList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" width="300" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <template v-if="row.type === 'toggle'">
              <el-tag
                :type="row.status === 1 ? 'success' : 'danger'"
                style="cursor: pointer"
                @click="handleStatusChange(row)"
              >
                {{ row.status === 1 ? "启用" : "禁用" }}
              </el-tag>
            </template>
            <template v-else>
              <el-tag type="info">
                {{ row.status }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="updated_at" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑系统设置"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" disabled placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            disabled
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <template v-if="editForm.type === 'toggle'">
            <el-switch
              v-model="editForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
            />
          </template>
          <template v-else>
            <el-input-number
              v-model="editForm.status"
              :min="0"
              controls-position="right"
              placeholder="请输入数值"
            />
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getSystemSetting, updateSystemSetting } from "@/api";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

interface SettingItem {
  id: number;
  name: string;
  description: string;
  status: number;
  created_at: string;
  updated_at: string;
  type: "toggle" | "value";
}

const settingList = ref<SettingItem[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const editForm = reactive({
  id: 0,
  name: "",
  description: "",
  status: 0,
  type: "toggle" as "toggle" | "value"
});

const rules = reactive<FormRules>({
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
});

const fetchData = async () => {
  try {
    const response = await getSystemSetting({
      page: currentPage.value,
      size: pageSize.value
    });

    if (response.status === "success") {
      settingList.value = response.data.records;
      total.value = response.data.pagination.total;
    }
  } catch (error) {
    console.error("获取系统设置失败:", error);
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchData();
};

const handleStatusChange = async (row: SettingItem) => {
  if (row.type !== "toggle") return;

  try {
    const newStatus = row.status === 1 ? 0 : 1;
    const response = await updateSystemSetting({
      id: row.id,
      status: newStatus
    });

    if (response.status === "success") {
      ElMessage.success(`状态修改${newStatus === 1 ? "启用" : "禁用"}成功`);
      row.status = newStatus;
    }
  } catch (error) {
    console.error("修改状态失败:", error);
    ElMessage.error("修改状态失败");
  }
};

const handleEdit = (row: SettingItem) => {
  editForm.id = row.id;
  editForm.name = row.name;
  editForm.description = row.description;
  editForm.status = row.status;
  editForm.type = row.type;
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        const response = await updateSystemSetting({
          id: editForm.id,
          status: editForm.status
        });

        if (response.status === "success") {
          ElMessage.success("修改成功");
          dialogVisible.value = false;
          fetchData(); // 刷新列表
        }
      } catch (error) {
        console.error("修改系统设置失败:", error);
        ElMessage.error("修改失败");
      }
    }
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.setting-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
